package membership_v1

import (
	"context"
	v1 "gf-xb-api/api/membership/v1"
	"gf-xb-api/cwt/mymiddleware"
	"gf-xb-api/internal/consts"
	"gf-xb-api/utility/xpermission"
	"gf-xb-api/utility/xredis"

	"github.com/gogf/gf/v2/database/gredis"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/util/gconv"
)

func (s *sMembership) RefreshToken(ctx context.Context) (res *v1.RefreshTokenRes, err error) {

	r := g.RequestFromCtx(ctx)
	uuid := xpermission.GetLoginUserUUID(ctx)
	deviceType := r.GetCtxVar(consts.JWT_INFO_DEVICETYPE).Int()

	token, _ := mymiddleware.Auth().RefreshHandler(ctx)

	redisKey := xredis.JwtTokenKey(uuid, deviceType)
	timeoutSeconds := g.Config().MustGet(ctx, consts.JWT_TIMEOUT).Int()
	expiry := gconv.PtrInt64(timeoutSeconds)

	g.Redis().Set(ctx, redisKey, token, gredis.SetOption{
		TTLOption: gredis.TTLOption{
			EX: expiry,
		},
	})

	res = &v1.RefreshTokenRes{
		Token:    token,
		ExpireIn: timeoutSeconds, // 单位秒
	}

	return res, nil
}
